#!/usr/bin/env python3
# -*- coding: utf-8 -*-
import os
import sys
import subprocess
import time
import shutil

def clear_folder(folder_path):
    """清空指定文件夹中的所有文件"""
    if os.path.exists(folder_path):
        for filename in os.listdir(folder_path):
            file_path = os.path.join(folder_path, filename)
            try:
                if os.path.isfile(file_path) or os.path.islink(file_path):
                    os.unlink(file_path)
                elif os.path.isdir(file_path):
                    shutil.rmtree(file_path)
            except Exception as e:
                print(f'删除 {file_path} 时出错: {e}')
        print(f'已清空文件夹: {folder_path}')

def run_script(script_path, script_name):
    """
    运行指定的Python脚本
    """
    try:
        print(f"开始运行 {script_name}...")
        start_time = time.time()
        
        # 使用subprocess运行脚本
        result = subprocess.run(
            [sys.executable, script_path],
            capture_output=True,
            text=True,
            encoding='utf-8',
            cwd=os.path.dirname(script_path)
        )
        
        end_time = time.time()
        duration = end_time - start_time
        
        if result.returncode == 0:
            print(f"✓ {script_name} 执行成功 (耗时: {duration:.2f}秒)")
            if result.stdout.strip():
                print(f"输出: {result.stdout.strip()}")
            return True
        else:
            print(f"✗ {script_name} 执行失败")
            if result.stderr:
                print(f"错误信息: {result.stderr}")
            if result.stdout:
                print(f"输出信息: {result.stdout}")
            return False
            
    except Exception as e:
        print(f"✗ 运行 {script_name} 时发生异常: {str(e)}")
        return False

def main():
    """
    主函数：依次运行三个脚本
    """
    # 清空输出文件夹
    current_dir = os.path.dirname(os.path.abspath(__file__))
    html_folder = os.path.join(current_dir, 'html')
    xml_folder = os.path.join(current_dir, 'xml')
    json_folder = os.path.join(current_dir, 'json')
    
    clear_folder(html_folder)
    clear_folder(xml_folder)
    clear_folder(json_folder)
    
    # 获取当前脚本所在目录
    current_dir = os.path.dirname(os.path.abspath(__file__))
    
    # 定义要运行的脚本列表
    scripts = [
        {
            'path': os.path.join(current_dir, 'A_doc_to_html.py'),
            'name': 'A_doc_to_html.py',
            'description': 'Word文档转HTML'
        },
        {
            'path': os.path.join(current_dir, 'B_html_to_xml.py'),
            'name': 'B_html_to_xml.py',
            'description': 'HTML转XML'
        },
        {
            'path': os.path.join(current_dir, 'E_xml_to_json.py'),
            'name': 'E_xml_to_json.py',
            'description': 'XML转JSON'
        }
    ]
    
    print("=" * 60)
    print("开始执行文档处理流程")
    print("=" * 60)
    
    total_start_time = time.time()
    success_count = 0
    
    # 依次运行每个脚本
    for i, script in enumerate(scripts, 1):
        print(f"\n[{i}/3] {script['description']}")
        print("-" * 40)
        
        # 检查脚本文件是否存在
        if not os.path.exists(script['path']):
            print(f"✗ 脚本文件不存在: {script['path']}")
            break
        
        # 运行脚本
        if run_script(script['path'], script['name']):
            success_count += 1
        else:
            print(f"\n✗ {script['name']} 执行失败，停止后续处理")
            break
    
    # 输出总结
    total_end_time = time.time()
    total_duration = total_end_time - total_start_time
    
    print("\n" + "=" * 60)
    print("执行完成")
    print("=" * 60)
    print(f"成功执行: {success_count}/3 个脚本")
    print(f"总耗时: {total_duration:.2f}秒")
    
    if success_count == 3:
        print("\n✓ 所有脚本执行成功！")
        print("文档处理流程完成：Word → HTML → XML → JSON")
        sys.exit(0)
    else:
        print(f"\n✗ 有 {3 - success_count} 个脚本执行失败")
        sys.exit(1)

if __name__ == "__main__":
    try:
        main()
    except KeyboardInterrupt:
        print("\n\n用户中断执行")
        sys.exit(1)
    except Exception as e:
        print(f"\n\n程序执行过程中发生未预期的错误: {str(e)}")
        sys.exit(1)